/**
 * Copyright (C), 2015-2019, 山东桔灯行信息科技有限公司
 * FileName: SinopecVerifyCardUtil
 * Author:   chen
 * Date:     19-5-21 下午4:07
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.duochuang.verifycard.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 〈一句话功能简述〉<br> 
 * 〈中石化卡号校验〉
 *
 * @author chen
 * @create 19-5-21
 * @since 1.0.0
 */
@Slf4j
public class SinopecVerifyCardUtil {
    private static String SINOPEC_COOKIE = "ticket=\"SSO-550_5TSKYUEPKKROZF5TUO9WY8O8H_H2NW0FSRFQII9FCPJIPMVPRZLIR9W1GVMY0O,687474703A2F2F31302E352E3138302E35353A383038302F77656273736F\"";

    public static VerifyCode verifyCard(String cardNo, String cookie) {
        Integer code = 0;
        String result = "";
        String url = "http://www.sinopecsales.com/gas/jsp/memberLoginAction_cardNoIsTrue.json";
//        String url = "http://www.sinopecsales.com/gas/jsp/memberLoginAction_cardNoIsTrue.json?cardNo={cardNo}";

        // 配置请求信息（请求时间）
        RequestConfig rc = RequestConfig.custom().setSocketTimeout(60000)
                .setConnectTimeout(60000).build();
        // 获取使用DefaultHttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            if (url != null) {
                // 创建HttpGet对象，将URL通过构造方法传入HttpGet对象
                HttpPost httpPost = new HttpPost(url);

                // 将配置好请求信息附加到http请求中
                httpPost.setConfig(rc);

                if (StringUtils.isEmpty(cookie)) {
                    cookie = SINOPEC_COOKIE;
                }

//                httpPost.setHeader("Connection", "keep-alive");
                httpPost.setHeader("Accept", " application/json, text/javascript, */*; q=0.01");
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36");
//                httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-us;q=0.6,en;q=0.5;q=0.4");

                // 获取cookie
                httpPost.addHeader("Cookie", cookie);
                // 构建消息实体
                StringEntity se = new StringEntity("cardNo=" + cardNo, Charset.forName("UTF-8"));
//                se.setContentEncoding("UTF-8");
                // 发送Json格式的数据请求
//	               se.setContentType("application/json");
                httpPost.setEntity(se);

                // 执行DefaultHttpClient对象的execute方法发送GET请求，通过CloseableHttpResponse接口的实例，可以获取服务器返回的信息
                CloseableHttpResponse response = httpclient.execute(httpPost);
                try {
                    // 得到返回对象
                    HttpEntity entity = response.getEntity();
                    System.out.println(response.getAllHeaders().clone().length);
                    for (Header h : response.getAllHeaders()) {
                        System.out.println(h);
                    }
//
//                    System.out.println();
//                    for (Header h : httpPost.getAllHeaders()) {
//                        System.out.println(h);
//
//                    }
                    if (entity != null) {
                        // 获取返回结果
                        result = EntityUtils.toString(entity, "GBK");
                        log.info("返回结果：{}", result);
                    }
                } finally {
                    // 关闭到客户端的连接
                    response.close();
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return new VerifyCode(code, "验证超时");
        } catch (IOException e) {
            e.printStackTrace();
            return new VerifyCode(code, "验证超时");
        } finally {
            try {
                // 关闭http请求
                httpclient.close();
            } catch (IOException e) {}
        }
        if (result.contains("请登录")) {
            return new VerifyCode(2, "中石化cookie过期，请重新获取");
        }
        try {
            JSONObject obj = JSONObject.parseObject(result);
            Integer status = obj.getInteger("success");
            // 只有 0：成功，-1：失败
            switch (status) {
                //卡号不存在
                case 2: {
                    result = "卡号不存在";
                    code = -1;
                    break;
                }
                case 7: {
                    result = "该加油卡未激活或无效!";
                    code = -1;
                    break;
                }
                case 5: {
                    result = "该绑定的卡为副卡!";
                    code = -1;
                    break;
                }
                case 8: {
                    result = "税务登记证号码信息未完善，请去加油站网点完善信息!";
                    code = -1;
                    break;
                }
                //("证件号码信息不匹配，请完善信息!");
                case 6:{
                    result = "证件号码信息不匹配";
                    code = 0;
                    break;
                }
                    // 证件号码信息不完善或有误，请完善信息!
                case 9: {
                    result = "证件号码信息不完善或有误";
                    code = -1;
                    break;
                }
                case 10: { //弹出浮层，要求修改税号或添加税号
                    result = "修改税号或添加税号";
                    code = -1;
                    break;
                }
                //成功;
                case 0:
                    //不需要短信验证
                case 1:
                    //电话号不存在
                case 3:
                    //加油卡已被绑定
                case 4: {
                    result = "卡号正常";
                    code = 0;
                    break;
                }
            }
        } catch (JSONException e) {
            log.error("中石化查询油卡返回结果 解析异常", e);
        }
        return new VerifyCode(code, result);
    }
}